<template>
  <div class="table-box">
    <div class="user-basic card mb10 pt0 pb0">
      <div class="select-filter-item-title" style="margin-top: 10px; color: #009688">
        <span>基本信息</span>
      </div>
      <el-divider style="margin: 8px 0 14px" />
      <el-form :inline="true">
        <el-form-item label="用户账号">
          <el-input v-model="userDetail.account" placeholder="Approved by" disabled />
        </el-form-item>
        <el-form-item label="用户昵称">
          <el-input v-model="userDetail.nickName" placeholder="Approved by" disabled />
        </el-form-item>
      </el-form>
    </div>

    <div class="auth-role">
      <ProTable
        ref="proTable"
        title="授权角色列表"
        :columns="columns"
        :request-api="getTableList"
        :init-param="initParam"
        :data-callback="dataCallback"
        :toolButton="false"
        rowKey="roleId"
      >
        <!-- 表格 header 按钮 -->
        <template #tableHeader>
          <div class="select-filter-item-title" style="margin-bottom: 15px; color: #009688">
            <span>角色信息</span>
          </div>
        </template>
      </ProTable>
      <div class="proTable-footer" style="margin-top: 10px; text-align: center">
        <el-button @click="closePage">返回</el-button>
        <el-button type="primary" @click="handleSubmit(proTable?.selectedListIds)" v-permission="'systemUserAuthRoleAddBatch'"
          >确定</el-button
        >
      </div>
    </div>
  </div>
</template>

<script setup lang="tsx" name="systemUserAuthRole">
import { ref, reactive } from "vue";
import { useRoute, useRouter } from "vue-router";
import { ProTableInstance, ColumnProps } from "@/components/ProTable/interface";
import { useTabsStore } from "@/stores/modules/tabs";
import ProTable from "@/components/ProTable/index.vue";
import { useKeepAliveStore } from "@/stores/modules/keepAlive";
import { getUserAuthRoleApi, getUserDetailApi, addUserAuthRoleBatchApi } from "@/api/modules/systemUser";
import { SystemUser } from "@/api/interface/systemUser";

const route = useRoute();
const router = useRouter();
const tabStore = useTabsStore();
const keepAliveStore = useKeepAliveStore();

const userId: number = parseInt(router.currentRoute.value.query.userId as string);

const userDetail = ref<Partial<SystemUser.UserDetailRes>>({});
// 获取用户详情
const getUserDetail = (userId: number) => {
  getUserDetailApi(userId).then(res => {
    if (res.isSuccessful) {
      userDetail.value = res.data;
    }
  });
};
getUserDetail(userId);

// 获取 ProTable 元素，调用其获取刷新数据方法（还能获取到当前查询参数，方便导出携带参数）
const proTable = ref<ProTableInstance>();

// 如果表格需要初始化请求参数，直接定义传给 ProTable(之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive({
  userId: userId
});

// dataCallback 是对于返回的表格数据做处理，如果你后台返回的数据不是 list && total && pageNum && pageSize 这些字段，那么你可以在这里进行处理成这些字段
// 或者直接去 hooks/useTable.ts 文件中把字段改为你后端对应的就行
const dataCallback = (data: any) => {
  return {
    list: data.rows,
    total: data.total,
    pageNum: data.pageNum,
    pageSize: data.pageSize
  };
};

// 如果你想在请求之前对当前请求参数做一些操作，可以自定义如下函数：params 为当前所有的请求参数（包括分页），最后返回请求列表接口
// 默认不做操作就直接在 ProTable 组件上绑定	:requestApi="getUserList"
const getTableList = (params: any) => {
  return getUserAuthRoleApi(params);
};

// 表格配置项
const columns = reactive<ColumnProps<SystemUser.UserAuthRoleRes>[]>([
  { type: "selection", fixed: "left" },
  {
    prop: "roleId",
    label: "角色编号"
  },
  {
    prop: "roleName",
    label: "角色名称"
  },

  {
    prop: "roleKey",
    label: "权限字符"
  },
  {
    prop: "createTime",
    label: "创建时间"
  }
]);

// 需要延迟勾选已有角色
setTimeout(() => {
  proTable.value?.tableData.forEach((v, k) => {
    if (v.isOwn) {
      proTable.value?.element?.toggleRowSelection(proTable.value?.tableData[k], true);
    }
  });
}, 500);

// 关闭页面
const closePage = () => {
  if (route.meta.isAffix) return;
  tabStore.removeTabs(route.fullPath);
  keepAliveStore.removeKeepAliveName(route.name as string);
};

// 提交
const handleSubmit = async (roleIds: string[] | undefined) => {
  let roleIdNews: number[] = [];
  if (undefined != roleIds && roleIds.length > 0) {
    roleIdNews = roleIds.map(Number);
  }
  const addRoleReq: SystemUser.UserAuthRoleAddBatchReq = {
    userId: userId,
    roleIds: roleIdNews
  };
  await addUserAuthRoleBatchApi(addRoleReq).then(res => {
    if (res.isSuccessful) {
      closePage();
    }
  });
};
</script>
